08. Exercise: Friends
Friend
Friends
In C++,
friend
classes provide an alternative inheritance mechanism to derived classes. The main difference between classical inheritance and friend inheritance is that a
friend
class can access private members of the base class, which isn't the case for classical inheritance. In classical inheritance, a derived class can only access public and protected members of the base class.
Instructions
In this exercise you will experiment with friend classes. In the notebook below, implement the following steps:
-
Declare a class
Rectangle. -
Define a class
Square. -
Add class
Rectangleas a friend of the classSquare. -
Add a private attribute
sideto classSquare. -
Create a public constructor in class
Squarethat initializes thesideattribute. -
Add private members
widthandheightto classRectangle. -
Add a
Rectangle()constructor that takes aSquareas an argument. -
Add an
Area()function toclass Rectangle.
Workspace
This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.
Workspace Information:
- Default file path:
- Workspace type: jupyter
- Opened files (when workspace is loaded): n/a